<template>
  <el-upload
      ref="upload"
      class="upload-demo"
      drag
      action="string"
      :limit="1"
      :http-request="uploadFile"
      :file-list="fileList"
      :on-exceed="handleExceed"
      :auto-upload="false"
      crossorigin="anonymous"
      accept="image/jpeg"
      with-credentials
  >
    <el-icon class="el-icon--upload">
      <upload-filled/>
    </el-icon>
    <div class="el-upload__text">
      Drop file here or <em>click to upload</em>
    </div>
    <template #tip>
      <div class="el-upload__tip">
        upload single jpg/png file < 1.00M
      </div>
    </template>
  </el-upload>
  <div id="ButtonContainer">
    <el-button type="success" @click="submitUpload">
      Detect
    </el-button>
    <el-button type="primary" @click="cameraHandler">
      Camera
    </el-button>
    <el-button type="warning" @click="switchHandler" icon="Switch" round>
    </el-button>
    <el-button type="danger" @click="captureHandler" icon="Camera" round>
    </el-button>
  </div>
  <br>
  <br>
  <div class="img-container">
    <el-image style="width: 49%;" :src="imgUrl1" fit="cover">
      <template #error>
        <div class="image-slot">
          <el-icon>
            <PictureFilled/>
          </el-icon>
        </div>
      </template>
    </el-image>
    <el-image style="width: 49%;" :src="imgUrl2" fit="cover">
      <template #error>
        <div class="image-slot">
          <el-icon>
            <PictureFilled/>
          </el-icon>
        </div>
      </template>
    </el-image>
    <el-image style="width: 97%;" :src="imgUrl3" ref="img3" fit="cover">
      <template #error>
        <div class="image-slot">
          <el-icon>
            <PictureFilled/>
          </el-icon>
        </div>
      </template>
    </el-image>
  </div>
  <br>
  <div id="CameraContainer">
    <video id="Video" ref="video" autoplay></video>
    <canvas id="Output" ref="output"></canvas>
  </div>
  <br>
</template>

<script setup>
import {ref} from 'vue'
import {genFileId} from 'element-plus'
import axios from "axios";
import {useGlobalStore} from "@/PiniaStore/global";
import FormData from "form-data";

const GlobalStore = useGlobalStore()

const upload = ref()
const fileList = ref([])
const imgUrl1 = ref()
const imgUrl2 = ref()
const imgUrl3 = ref()
const img3 = ref()

function uploadFile(item) {
  console.log(item)
  const FormData = require('form-data');
  let data = new FormData();
  data.append('img', item.file);
  console.log(data)
  let config = {
    method: 'post',
    maxBodyLength: Infinity,
    url: 'http://' + GlobalStore.origin + '/api/yolo',
    headers: {},
    data: data
  };
  const intervalTime = 1000 * 3
  let intervalId = setInterval(() => {
    axios.request(config)
        .then((response) => {
          let data = response.data
          console.log(data)
          if (data.status === "done") {
            clearInterval(intervalId)
            console.log(data.result)
            imgUrl1.value = "http://" + GlobalStore.origin + "/static/yolo/" + data.result
            imgUrl2.value = "http://" + GlobalStore.origin + "/static/yolo/result/" + data.result.replace(".png", ".jpg")
          }
        })
        .catch((error) => {
          console.log(error);
        });
  }, intervalTime)
  // let data_hhb = new FormData()
  // data_hhb.append("imgName", item.file.name)
  // console.log(data_hhb)
  // let config_hhb = {
  //   method: 'post',
  //   maxBodyLength: Infinity,
  //   url: 'http://' + GlobalStore.origin + '/api/yolo_hhb',
  //   headers: {},
  //   data: data_hhb
  // };
  // let intervalHHB = setInterval(() => {
  //   axios.request(config_hhb)
  //       .then((response) => {
  //         let data = response.data
  //         console.log(data)
  //         if (data.status === "done") {
  //           clearInterval(intervalHHB)
  //           console.log(data.result)
  //           imgUrl3.value = "http://" + GlobalStore.origin + "/static/yolo/result/hhb/" + data.result
  //         }
  //       })
  //       .catch((error) => {
  //         console.log(error);
  //       });
  // }, intervalTime)
}

const handleExceed = (files) => {
  console.log(files)
  upload.value.clearFiles()
  let file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}

const submitUpload = () => {
  upload.value.submit()
}

const video = ref()
const output = ref()
const isFirstCamera = ref(true)
const cameraMode = ref("user")
const cameraHandler = () => {
  let success = function (stream) {
    console.log('摄像头开启成功')
    alert('摄像头开启成功')
    video.value.srcObject = stream
    video.value.play()
    if (isFirstCamera.value) {
      isFirstCamera.value = false
      video.value.style.height = "unset"
      video.value.style.opacity = 1
      output.value.style.height = "unset"
      output.value.style.opacity = 1
    }
  }
  let error = (error) => {
    alert('摄像头调用失败')
    console.log(error)
  }
  navigator.getUserMedia = navigator.getUserMedia ||
      navigator.mediaDevices.getUserMedia ||
      navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia ||
      navigator.msGetUserMedia
  navigator.getUserMedia({video: {facingMode: cameraMode.value}, audio: false}, success, error)
}

const switchHandler = () => {
  if (cameraMode.value === "user") {
    cameraMode.value = "environment"
  } else {
    cameraMode.value = "user"
  }
  cameraHandler()
}

function base64toFile(dataurl, filename = 'file') {
  let arr = dataurl.split(',')
  let mime = arr[0].match(/:(.*?);/)[1]
  let suffix = mime.split('/')[1]
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], `${filename}.${suffix}`, {
    type: mime
  })
}

const captureHandler = () => {
  if (video.value.srcObject) {
    let canvas = output.value
    let ctx = canvas.getContext('2d')
    let width = video.value.videoWidth
    let height = video.value.videoHeight
    canvas.width = width
    canvas.height = height
    ctx.drawImage(video.value, 0, 0, width, height)
    let imgData = canvas.toDataURL("image/jpg")
    console.log(imgData)
    upload.value.clearFiles()
    let uid = genFileId()
    let file = base64toFile(imgData, uid)
    file.uid = uid
    upload.value.handleStart(file)
  } else {
    alert("请先打开摄像头")
  }
}
</script>

<style scoped lang="less">
.img-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;

  .el-image {
    margin: 0 3px 17px 3px;
  }

  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
  }
}

#ButtonContainer {
  display: flex;
  flex-wrap: wrap;
  width: 100%;

  button.el-button {
    margin: 7px 14px 3px 0;
  }
}

#CameraContainer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;

  video#Video, canvas#Output {
    border: 3px solid var(--main-blue);
    border-radius: 17px;
    width: 47%;
    aspect-ratio: 16 / 9;
    transition: var(--transition);
    height: 0;
    opacity: 0;
  }
}

@media screen and (max-width: 900px) {
  #ButtonContainer {
    justify-content: center;
  }

  .el-image {
    width: 100% !important;
  }
}
</style>